package com.io.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

public class ChatClient {

    private static final String IP="127.0.0.1";
    private static final int PORT=6379;
    private SocketChannel socketChannel;
    private Selector selector;
    private String username;

    public ChatClient() {
        try {
            //连接服务器,并且得到连接服务器的通道
            socketChannel = SocketChannel.open(new InetSocketAddress(IP, PORT));
            //设置为非阻塞，好像每得到一个通道都要设置为非阻塞
            socketChannel.configureBlocking(false);
            //得到selector
            selector = Selector.open();
            //注册通道到selector上,事件为只读(这里是写的多通道的情况，一般好像是一个通道)
            socketChannel.register(selector, SelectionKey.OP_READ);
            //获取自己的ip
            username = socketChannel.getLocalAddress().toString().substring(1);
            System.out.println(username+" is ok......");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //向服务器发送消息
    public void sendInfo(String info) {
        info = username + " 说：" + info;
        try {//将信息写入通道
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    //读取从服务器端回复的消息
    public void readInfo() {
        try {//等待看看是否有发生事件的通道
            int count = selector.select();
            if(count > 0) {//有发生事件的通道
                //得到selectedKeys的迭代器
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                //遍历迭代器，进行相关的业务处理
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if(key.isReadable()) {
                        //得到相关的通道
                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        //得到一个Buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        //读取
                        socketChannel.read(buffer);
                        //把读到的缓冲区的数据转成字符串
                        String msg = new String(buffer.array());
                        System.out.println(msg);
                    }
                }
                iterator.remove(); //删除当前的SelectionKey
            } else {
                //System.out.println("没有可以用的通道...");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ChatClient chatClient = new ChatClient();

        //这个线程一直在读取消息，客户端里面又两个线程在工作
        new Thread(){
            public void run() {
                while (true){
                    try {
                        chatClient.readInfo();
                        Thread.sleep(1*1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        //主线程一直在发送消息
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String msg = scanner.nextLine();
            chatClient.sendInfo(msg);
        }

    }

}
